# -*- coding: utf-8 -*-
'''
Copyright(C) 2013 "Kevin Xu <ssonxu@gmail.com>"

This file is part of acqu-center.

acqu-center is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

acqu-center is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with acqu-center.  If not, see <http://www.gnu.org/licenses/>.
'''
import logging
from Predef import Predef as PRE
from google.appengine.ext import ndb
from parser import parser as ROCK


class RSSItem(ndb.Model):
    title = ndb.StringProperty(required=True)
    link = ndb.StringProperty(required=True)
    description = ndb.StringProperty(required=True)
    guid = ndb.StringProperty(required=True)
    pubDate = ndb.StringProperty(required=True)
    media = ndb.BlobProperty(indexed=False)

    ############
    # process
    ############

class RSS(ndb.Model):
    ############
    # Initialize
    ############
    title = ndb.StringProperty(required=True)
    url = ndb.StringProperty(required=True,default=PRE.url_)
    description = ndb.StringProperty(indexed=False,default='')
    language = ndb.StringProperty(default='')
    lastBuildDate = ndb.StringProperty(default='')
    storyexpression = ndb.StringProperty(indexed=False)
    items = ndb.StructuredProperty(RSSItem, repeated=True, indexed=False)

    catagory = ndb.StringProperty(default='')
    isRunning = ndb.BooleanProperty(default=False)


    ############
    # process
    ############
    def ID(self):
        return self.key.id()

    def lauchIt(self):
        self.isRunning=True
        self.put()

    def drawbackIt(self):
        self.isRunning=False
        self.put()

    #def exportData(self):
    #    return [ x.val for x in self.stuffs ]

    #def export(self):
    #    ex = self.to_dict(exclude=['stuffs'])
    #    ex['stuffs']=[ x.to_dict(exclude=['val']) for x in self.stuffs ]
    #    return ex

    ############
    # class
    ############
    @classmethod
    def newRSS(cls, u):
        if cls.getRSS(u) is not None:
            return cls.getRSS(u)
        else:
            try:
                t,d,l,p = PRE.getRSS( u )
                return RSS(title=t, url=u, description=d, language=l, lastBuildDate=p)
            except urlfetch.Error, e:
                logging.error(e)
                return None

    #def getMenu(cls, Running=False):
    #    res=[]
    #    ll=cls.listBoxes(Running=True)
    #    for x in ll:
    #        res.append(u"{}. {} - {}".format(x.ID(), x.label, x.description))

    #    return u'\n\n'.join(res)

    @classmethod
    def listRSS(cls, Running=False, Limit=None, Offset=0):
        query = cls.query(cls.isRunning == Running)
        return query.fetch(limit=Limit, offset=Offset)

    @classmethod
    def getRSS(cls, url):
        query = cls.query(cls.url == url)
        return query.get()

    @staticmethod
    def getBoxByID(ID):
        return ndb.Key(Box, ID).get()

    @classmethod
    def delBoxByID(cls, ID):
        b = Box.getBoxByID(ID)
        if b is not None:
            return b.key.delete()
        return None
        
    @classmethod
    def rockMe(cls):
        for x in cls.listRSS(Running=True):
            ROCK(x).run()
            x.put()

    ############
    # export & import
    ############
    @classmethod
    def exportDict(cls, label=None):
        if label is None:
            return [p.export() for p in cls.query().fetch()]
        else:
            return Box.getBox(label).export()

    @classmethod
    def importDict(cls, dic):
        for d in dic:
            b=Box( label=d['label'],isRunning=d['isRunning'],description=d['description'],url=d['url'],
                    catagory=d['catagory'] )
            b.stuffs=[]
            for s in d['stuffs']: 
                st=Stuff( pattern=s['pattern'], message=s['message'], expression=s['expression'], p1=s['p1'], p2=s['p2'],
                        val=['0']) 
                b.stuffs.append(st)
            b.put()
